<template>
  <div class="create-post-page">
    <h4>{{ isEditMode ? '编辑文章' : '新建文章' }}</h4>
    <uploader
      action="/upload"
      :beforeUpload="uploadCheck"
      @file-uploaded="handleFileUploaded"
      :uploaded="uploadedData"
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
    >
      <h2>点击上传头图</h2>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" role="status">
            <span class="visually-hidden">Loading...</span>
          </div>
          <h2>正在上传</h2>
        </div>
      </template>
      <template #uploaded="dataProps">
        <img :src="dataProps.uploadedData.data.url" alt="">
      </template>
    </uploader>
    <!-- <input type="file" name="file" @change.prevent="handleFileChange"/> -->
    <validate-form @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="form-label">文章标题：</label>
        <validate-input
          :rules="titleRules"
          placeholder="请输入文章标题"
          type="text"
          v-model="titleVal"
        />
      </div>
      <div class="mb-3">
        <label class="form-label">文章详情：</label>
        <validate-input
          rows="10"
          tag="textarea"
          placeholder="请输入文章详情"
          :rules="contentRules"
          v-model="contentVal"
        />
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">{{ isEditMode ? '更新文章' : '发表文章' }}</button>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { GlobalDataProps, PostProps, ResponseType, ImageProps } from '../store'
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import ValidateForm from '../components/ValidateForm.vue'
import Uploader from '../components/Uploader.vue'
import createMessage from '../components/createMessage'

import { beforeUploadCheck } from '../helper'

export default defineComponent({
  name: 'Login',
  components: {
    ValidateInput,
    ValidateForm,
    Uploader
  },
  setup() {
    const titleVal = ref('')
    const router = useRouter()
    // 使用 useRoute 来获取参数，编辑和创建时参数不同:根据 route.query.id 来判断
    const route = useRoute()
    // 将 route.query.id 转换为 布尔类型，使用 isEditMode 来判断是否是编辑模式
    // 新建一个响应式对象uploadedData表明上传的内容
    const uploadedData = ref()
    const isEditMode = !!route.query.id
    const store = useStore<GlobalDataProps>()
    let imageId = ''
    const titleRules: RulesProp = [
      { type: 'require', message: '文章标题不能为空' }
    ]
    const contentVal = ref('')
    const contentRules: RulesProp = [
      { type: 'require', message: '文章详情不能为空' }
    ]
    onMounted(() => {
      if (isEditMode) {
        // 如果是编辑模式就发送请求
        store.dispatch('fetchPost', route.query.id).then((rawData: ResponseType<PostProps>) => {
          const currentPost = rawData.data
          if (currentPost.image) {
            uploadedData.value = { data: currentPost.image }
          }
          titleVal.value = currentPost.title
          contentVal.value = currentPost.content || ''
        })
      }
    })
    // 拿 imageid 的方法
    // 这里的 rawData 应该是一个 ResponseType（符合后端定义的）,并且是一个ImageProps 的
    const handleFileUploaded = (rawData: ResponseType<ImageProps>) => {
      // 如果图片存在就拿它的id
      if (rawData.data._id) {
        imageId = rawData.data._id
      }
    }
    const onFormSubmit = (result: boolean) => {
      if (result) {
        const { column, _id } = store.state.user
        if (column) {
          const newPost: PostProps = {
            title: titleVal.value,
            content: contentVal.value,
            column,
            author: _id
          }
          // 异步请求：如果有图片的情况下发送
          if (imageId) {
            newPost.image = imageId
          }
          // 更新 store.dispatch
          // 确定是新建还是更新
          const actionName = isEditMode ? 'updatePost' : 'createPost'
          // 确定发送新数据还是创建数据
          const sendData = isEditMode ? { id: route.query.id, payload: newPost } : newPost
          store.dispatch(actionName, sendData).then(() => {
            createMessage('发表成功，2秒后跳转到专栏页', 'success', 2000)
            setTimeout(() => {
              router.push({ name: 'column', params: { id: column } })
            })
          })
        }
      }
    }
    const uploadCheck = (file: File) => {
      // 将 result 的值通过刚刚定义的 beforeUploadCheck 进行检查
      const result = beforeUploadCheck(file, { format: ['image/jpeg', 'image/png'], size: 1 })
      // 然后将 beforeUploadCheck 得出的结果返回给 result 并取出放到 passed 和 error 中
      const { passed, error } = result
      // 如果是 format 有问题就弹出错误信息
      if (error === 'format') {
        createMessage('上传图片只能是JPG/PNG格式', 'error')
      }
      if (error === 'size') {
        createMessage('上传图片大小不能超过1MB', 'error')
      }
      return passed
    }
    // const handleFileChange = (e: Event) => {
    //   // 先把 e.target 断言成 HTMLInputtarget，就能拿到其对应的属性了
    //   const target = e.target as HTMLInputElement
    // 通过 target.files 拿到文件，这个文件是个列表（FileList）array like object，不是个数组
    // const files = target.files
    // if (files) {
    //   // 把第一个上传的文件拿出来
    //   const uploadedFile = files[0]
    //   // 创建一个新的表单
    //   const formData = new FormData()
    //   // 然后将上传的文件的名字和文件本身添加到表单中去
    //   formData.append(uploadedFile.name, uploadedFile)
    //   axios.post('/upload', formData, {
    //     headers: {
    //       'Content-type': 'multipart/form-data'
    //     }
    //   }).then((resp) => {
    //     console.log(resp)
    //   })
    // }
    // }
    return {
      titleRules,
      titleVal,
      contentVal,
      contentRules,
      onFormSubmit,
      uploadCheck,
      handleFileUploaded,
      uploadedData,
      isEditMode
    }
  }
})
</script>
<style>
  .create-post-page .file-upload-container {
    height: 200px;
    cursor: pointer;
    overflow: hidden;
  }
  .create-post-page .file-upload-container img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>
